<template>
  <div class="add-house-container">
    <h2 class="title">新增房源信息</h2>

    <div class="form-wrapper">
      <el-form
          ref="houseForm"
          :model="formData"
          label-width="120px"
          label-position="top"
          :rules="rules"
          @submit.prevent="submitForm"
      >
        <el-tabs type="border-card" class="form-tabs">
          <!-- 基础信息 -->
          <el-tab-pane label="基础信息">
            <div class="tab-content">
              <el-form-item label="房源标题" prop="title">
                <el-input v-model="formData.house.title" placeholder="请输入房源标题" />
              </el-form-item>

              <el-form-item label="房源状态" prop="status">
                <el-select
                    v-model="formData.house.status"
                    placeholder="请选择房源状态"
                    style="width: 100%"
                >
                  <el-option label="待审核" value="pending" />
                  <el-option label="已发布" value="published" />
                  <el-option label="已出租" value="rented" />
                  <el-option label="维护中" value="maintenance" />
                  <el-option label="已下架" value="offline" />
                </el-select>
              </el-form-item>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="物业类型" prop="property_type">
                    <el-select
                        v-model="formData.house.property_type"
                        placeholder="请选择物业类型"
                        style="width: 100%"
                    >
                      <el-option label="请选择" value=""></el-option>
                      <el-option label="公寓" value="公寓" />
                      <el-option label="别墅" value="别墅" />
                      <el-option label="商铺" value="商铺" />
                      <el-option label="房间" value="房间" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="租赁类型" prop="rental_type">
                    <el-select
                        v-model="formData.house.rental_type"
                        placeholder="请选择租赁类型"
                        style="width: 100%"
                    >
                      <el-option label="请选择" value=""></el-option>
                      <el-option label="整租" value="整租" />
                      <el-option label="合租" value="合租" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="面积(㎡)" prop="area">
                    <el-input-number
                        v-model.number="formData.house.area"
                        :min="1"
                        style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="价格(元/月)" prop="price">
                    <el-input-number
                        v-model.number="formData.house.price"
                        :min="1"
                        style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="押金(元)">
                    <el-input-number
                        v-model.number="formData.house.deposit"
                        :min="0"
                        style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="卧室数量">
                    <el-input-number
                        v-model.number="formData.house.bedroom_count"
                        :min="0"
                        style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客厅数量">
                    <el-input-number
                        v-model.number="formData.house.livingroom_count"
                        :min="0"
                        style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="卫生间数量">
                    <el-input-number
                        v-model.number="formData.house.bathroom_count"
                        :min="0"
                        style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>

          <!-- 地址信息 -->
          <el-tab-pane label="地址信息">
            <div class="tab-content">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="省份" prop="province">
                    <el-input v-model="formData.address.province" placeholder="请输入省份" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="城市" prop="city">
                    <el-input v-model="formData.address.city" placeholder="请输入城市" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="区县" prop="district">
                    <el-input v-model="formData.address.district" placeholder="请输入区县" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="街道">
                    <el-input v-model="formData.address.street" placeholder="请输入街道" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="详细地址">
                <el-input
                    v-model="formData.address.location"
                    placeholder="请输入详细地址"
                    type="textarea"
                    :rows="3"
                />
              </el-form-item>
            </div>
          </el-tab-pane>

          <!-- 设施信息 -->
          <el-tab-pane label="设施信息">
            <div class="tab-content">
              <el-form-item label="设施配置">
                <el-checkbox-group
                    v-model="facilitySelected"
                    class="facility-checkbox-group"
                >
                  <el-row :gutter="20">
                    <el-col :span="8" v-for="item in facilityOptions" :key="item.value">
                      <el-checkbox
                          :label="item.value"
                      >
                        {{ item.label }}
                      </el-checkbox>
                    </el-col>
                  </el-row>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="form-actions">
          <el-button @click="cancel" size="large">取消</el-button>
          <el-button type="primary" @click="submitForm" size="large">提交</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'
import common_util from '../../util/common_util.js'
import { useRouter } from 'vue-router'

const router = useRouter()

// 设施选项配置
const facilityOptions = [
  { value: 'has_lift', label: '电梯' },
  { value: 'has_parking', label: '停车位' },
  { value: 'has_wifi', label: 'WiFi' },
  { value: 'has_kitchen', label: '厨房' },
  { value: 'has_washer', label: '洗衣机' },
  { value: 'has_ac', label: '空调' },
  { value: 'has_heating', label: '暖气' },
  { value: 'has_tv', label: '电视' }
]

// 表单数据
const formData = reactive({
  house: {
    title: '阳光花园3号楼201室',
    property_type: '公寓',
    rental_type: '整租',
    area: 85,
    price: 3800,
    deposit: 3800,
    bedroom_count: 2,
    livingroom_count: 1,
    bathroom_count: 1,
    status: 'published'
  },
  address: {
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    street: '朝阳北路101号',
    location: {
      type: 'Point',
      coordinates: [116.520, 39.930] // 朝阳区坐标
    }
  },
  facility: {
    has_lift: true,
    has_parking: true,
    has_wifi: true,
    has_kitchen: true,
    has_washer: true,
    has_ac: true,
    has_heating: true,
    has_tv: false
  }
})

// 计算属性：处理设施选择的双向绑定
const facilitySelected = computed({
  get() {
    return Object.entries(formData.facility)
        .filter(([_, value]) => value)
        .map(([key]) => key)
  },
  set(newVal) {
    // 重置所有设施为false
    Object.keys(formData.facility).forEach(key => {
      formData.facility[key] = false
    })
    // 将选中的设施设为true
    newVal.forEach(key => {
      formData.facility[key] = true
    })
  }
})

// 表单验证规则
const rules = reactive({
  'house.title': [{ required: true, message: '请输入房源标题', trigger: 'blur' }],
  'house.property_type': [{ required: true, message: '请选择物业类型', trigger: 'change' }],
  'house.rental_type': [{ required: true, message: '请选择租赁类型', trigger: 'change' }],
  'house.area': [{ required: true, message: '请输入面积', trigger: 'blur' }],
  'house.price': [{ required: true, message: '请输入价格', trigger: 'blur' }],
  'house.status': [{ required: true, message: '请选择房源状态', trigger: 'change' }],
  'address.province': [{ required: true, message: '请输入省份', trigger: 'blur' }],
  'address.city': [{ required: true, message: '请输入城市', trigger: 'blur' }],
  'address.district': [{ required: true, message: '请输入区县', trigger: 'blur' }]
})

// 提交表单
const submitForm = async () => {
  try {
    const loading = ElLoading.service({ text: '提交中...' })

    // 验证必填字段
    if (!formData.house.title || !formData.house.property_type ||
        !formData.house.rental_type || !formData.house.area ||
        !formData.house.price) {
      throw new Error('请填写所有必填字段')
    }

    // 验证地址信息
    if (!formData.address.province || !formData.address.city ||
        !formData.address.district) {
      throw new Error('请填写完整的地址信息')
    }

    // 获取用户ID
    const userResponse = await axios.get('/api/user_info', {
      headers: common_util.accessHeader()
    })

    if (userResponse.data.code !== 0) {
      throw new Error('获取用户信息失败')
    }

    formData.house.userid = Number(userResponse.data.data.userId)

    // 处理位置数据 - 确保符合GeoJSON格式
    if (typeof formData.address.location === 'string') {
      try {
        // 尝试解析字符串格式的位置
        const [lng, lat] = formData.address.location
            .replace('POINT(', '')
            .replace(')', '')
            .split(' ')
            .map(Number)

        formData.address.location = {
          type: 'Point',
          coordinates: [lng, lat]
        }
      } catch (e) {
        throw new Error('位置格式不正确，请使用"POINT(经度 纬度)"格式')
      }
    }

    console.log('准备提交的数据:', JSON.stringify(formData, null, 2))

    // 发送请求
    const response = await axios.post('/api/houses', formData, {
      headers: common_util.accessHeader()
    })

    loading.close()

    if (response.data.code === 0) {
      ElMessage.success('房源创建成功')
      router.push({
        name: 'LandlordUploadImages',
        params: { houseId: response.data.data.houseid }
      })
    } else {
      throw new Error(response.data.extra_msg || '创建房源失败')
    }
  } catch (error) {
    ElLoading.service().close()
    console.error('提交失败详情:', error)

    let errorMsg = error.message
    if (error.response) {
      // 处理后端返回的错误信息
      errorMsg = error.response.data?.message ||
          error.response.data?.extra_msg ||
          '服务器错误'

      // 如果是验证错误，显示更详细的错误信息
      if (error.response.data?.code === 400) {
        errorMsg = error.response.data.extra_msg || '数据验证失败'
      }
    }

    ElMessage.error(errorMsg)
  }
}

// 取消
const cancel = () => {
  router.go(-1)
}

// 初始化
onMounted(() => {
  // 可以在这里添加初始化逻辑
})
</script>

<style scoped>
.add-house-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.title {
  margin-bottom: 20px;
  text-align: center;
  font-size: 24px;
  color: #333;
}

.form-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.tab-content {
  height: 100%;
  overflow-y: auto;
  padding-right: 10px;
}

.el-form-item {
  margin-bottom: 22px;
}

.facility-checkbox-group {
  width: 100%;
}

.facility-checkbox-group .el-checkbox {
  display: flex;
  align-items: center;
  margin-right: 0;
  height: 40px;
}

.form-actions {
  margin-top: 20px;
  text-align: center;
  padding: 20px 0;
}

/* 自定义滚动条 */
.tab-content::-webkit-scrollbar {
  width: 6px;
}

.tab-content::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 3px;
}

.tab-content::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .add-house-container {
    padding: 10px;
    height: calc(100vh - 20px);
  }

  .el-col {
    margin-bottom: 15px;
  }

  .facility-checkbox-group .el-col {
    margin-bottom: 10px;
  }
}
</style>